<?php

namespace App\Trip\Payment;

use Exception;
use Illuminate\Support\Facades\Validator;

class PaymentAttach
{

    const PAY_TYPE_ORDER             = 1;
    const PAY_TYPE_APPLY_REFUND      = 3;
    const PAY_TYPE_SNAP_TASK_UPGRADE = 5;
    const PAY_TYPE_SNAP_TASK_EDIT    = 7;
    private array $attach;

    /**
     * @throws Exception
     */
    public function __construct(array $attach)
    {
        $this->setAttach($attach);
    }

    /**
     * @throws Exception
     */
    private function setAttach(array $attach): void
    {
        $validator = Validator::make($attach, [
            'type' => "required",
        ]);

        if ($validator->fails()) {
            throw new Exception("attach param error,type miss or fault");
        }


        $this->attach = $attach;
        if (mb_strlen($this) >= 127) {
            throw new Exception("attach len error");
        }
    }

    public function __toString()
    {
        return json_encode($this->attach, JSON_UNESCAPED_UNICODE);
    }

    public function toArray(): array
    {
        return json_decode($this, true);
    }

    /**
     * 支付时 是否选中加速包
     *
     * @return bool
     */
    public function isUpgradeSnapHeightLevel(): bool
    {
        if (!isset($this->attach['snap_level'])) {
            return false;
        }

        return $this->attach['snap_level'] == 4;
    }

    public function getType()
    {
        return $this->type;
    }

    /**
     * @throws Exception
     */
    public function __get($name)
    {
        if (!isset($this->attach[$name])) {
            throw new Exception("attach 属性 {$name}不存在");
        }
        return $this->attach[$name];
    }

}